<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>我的文件系统</title>
    <script th:src="@{/js/jquery.min.js}"></script>
    <script th:src="@{/js/bootstrap.bundle.js}"></script>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}">
    <style>
        .main {
            padding: 20px;
            margin: 20px;
        }

        .file-upload {
            margin: 0 auto;
            display: flex;
            justify-content: center;
            width: 50%;
        }

        #fileInput {
            display: inline-block;
        }

        #submit {
            margin: 0 20px;
        }

        .file-list {
            margin: 0 auto;
            padding: 30px;
        }

        .file-list>table>thead>tr>td {
            white-space: nowrap;
            font-weight: bolder;
        }

        .file-list .data>tr>td {
            font-size: 17px;
            line-height: 34px;
        }

        .file-list .data>tr>td>a {
            text-decoration: none;
        }

        .updatePwd-div {
            position: fixed;
            right: 80px;
            top: 5px;
            width: 100px;
            height: 50px;
            padding: 10px;
        }
        .whiteList-div {
            position: fixed;
            right: 5px;
            top: 5px;
            width: 100px;
            height: 50px;
            padding: 10px;
        }

        .file-list .data>tr>td:last-child>button {
            margin: 0 5px;
        }

        .btn-ip,.btn-del,.whiteList-div,.updatePwd-div {
            display: none;
        }

    </style>
</head>

<body>
<div class="main">
    <div class="file-upload">
        <div>
            <input class="form-control form-control-lg" id="fileInput" type="file">
        </div>
        <div>
            <!-- <button type="submit" class="btn btn-info btn-lg" id="submit" data-bs-toggle="modal" data-bs-target="#uploader">上传</button> -->
            <button type="submit" class="btn btn-info btn-lg" id="submit">上传</button>
        </div>
    </div>
    <div class="file-list">
        <table class="table table-hover">
            <thead>
            <tr>
                <td class="text-center">序号</td>
                <td>文件名称</td>
                <td class="text-center">上传时间</td>
                <td class="text-center">操作</td>
            </tr>
            </thead>
            <tbody class="data">

            </tbody>
        </table>
    </div>

    <div class="whiteList-div">
        <a href="#" id="updateWhiteList" data-bs-toggle="modal" data-bs-target="#updateWhiteListModal">修改白名单</a>
    </div>

    <div class="updatePwd-div">
        <a href="#" id="updatePwd" data-bs-toggle="modal" data-bs-target="#updatePwdModal">修改密码</a>
    </div>
</div>

<div class="modal fade" id="uploader" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="exampleModalLabel">上传人</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="mb-3">
                        <input type="text" class="form-control" id="uploader-name" placeholder="你的名字" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm-uploader">确定</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="updatePwdModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="updatePwdModalLabel">修改密码</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="mb-3">
                        <label for="old-pwd" class="col-form-label">旧密码：</label>
                        <input type="password" class="form-control" id="old-pwd" required>
                    </div>
                    <div class="mb-3">
                        <label for="new-pwd" class="col-form-label">新密码：</label>
                        <input type="password" class="form-control" id="new-pwd" required>
                    </div>
                    <div class="mb-3">
                        <label for="confirm-new-pwd" class="col-form-label">确认新密码：</label>
                        <input type="password" class="form-control" id="confirm-new-pwd" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm-update-pwd">确定</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="updateWhiteListModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="updateWhiteModalLabel">修改白名单</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form>
                    <div class="mb-3">
                        <input type="hidden" id="fileId">
                        <p id="fileName"></p>
                        <label for="white-list" class="col-form-label">白名单列表（多个用英文逗号隔开）：</label>
                        <textarea name="white-list" id="white-list" class="form-control" cols="30" rows="5"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm-update-white-list">确定</button>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        refreshFileList();
        isShowUpdatePwd();
    });

    function formRequest(url, formData, success) {
        $.ajax({
            url: url, // 服务器上传脚本的URL
            type: 'POST',
            data: formData,
            contentType: false, // 不设置内容类型
            processData: false, // 不处理发送的数据
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", sessionStorage.getItem("fileSystemToken"));
            },
            success: success,
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    }

    $('#submit').click(function () {
        // let name = $("#uploader-name").val();
        // if (name == null || name == '') {
        //     alert("姓名不能为空！");
        //     return;
        // }
        var formData = new FormData(); // 创建FormData对象
        formData.append("file", $("#fileInput")[0].files[0]);
        formData.append("uploader", name);
        formRequest("/upload", formData,
            function (response) {
                if(redirectLogin(response)) {
                    return;
                }
                alert(response);
                // $("#uploader").modal("hide");
                refreshFileList();
            }
        )
    });

    function refreshFileList() {
        $.ajax({
            url: '/fileList',
            type: 'GET',
            dataType: "json", // 期望从服务器返回的数据类型
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", sessionStorage.getItem("fileSystemToken"));
            },
            success: function (response) {
                if(redirectLogin(response)) {
                    return;
                }
                let tdHtml = "";
                for (let index in response) {
                    let ele = response[index];
                    let seq = Number(index) + 1;
                    tdHtml = tdHtml + "<tr><td class='text-center'>" + seq + "</td><td><a href='#' onclick='viewFile(this);' id='" + ele.id + "'>" + ele.fileName + "</a></td><td class='text-center'>" + ele.uploadTime + "</td><td class='text-center'><button onclick='setIp(this);' data-bs-toggle='modal' data-bs-target='#updateWhiteListModal' class='btn btn-info btn-ip'>限定IP</button><button onclick='deleteFile(this);' class='btn btn-danger btn-del'>删除</button></td></tr>";
                }
                $(".file-list .data").html(tdHtml);
                isShowUpdateWhiteList();
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    }

    function viewFile(obj) {
        let name = $(obj).text();
        let url = "http://" + window.location.host + "/view/" + name;
        let authInfo = sessionStorage.getItem("fileSystemToken");
        if(authInfo != null && authInfo != "" && authInfo != "null") {
            if(url.includes("?")) {
                url = url + "&auth_info=" + authInfo;
            } else {
                url = url + "?auth_info=" + authInfo;
            }
        }
        window.open(url);
    }

    function deleteFile(obj) {
        let fileName = $(obj).parent().siblings().eq(1).text();
        let fileId = $(obj).parent().siblings().eq(1).children("a").attr("id");
        let makeSure = confirm("真的要删除文件" + fileName + "吗？");
        if (!makeSure) {
            return;
        }
        let formData = new FormData();
        formData.append("id", fileId);
        formRequest('/deleteFile', formData,
            function (response) {
                if(redirectLogin(response)) {
                    return;
                }
                if (response == "0") {
                    refreshFileList();
                } else {
                    alert("删除失败");
                }
            }
        )
    }

    $("#confirm-update-pwd").click(function () {
        let oldPwd = $("#old-pwd").val();
        let newPwd = $("#new-pwd").val();
        let confirmNewPwd = $("#confirm-new-pwd").val();
        if (newPwd != confirmNewPwd) {
            alert("输入的两次新密码不一致");
            return;
        }
        let formData = new FormData();
        formData.set("oldPwd", oldPwd);
        formData.set("newPwd", newPwd);
        formRequest('/updatePwd', formData,
            function (response) {
                if(redirectLogin(response)) {
                    return;
                }
                if (response == "0") {
                    alert("密码修改成功");
                    $("#old-pwd").val("");
                    $("#new-pwd").val("");
                    $("#confirm-new-pwd").val("");
                    $("#updatePwdModal").modal("hide");
                } else {
                    alert("旧密码输入错误");
                }
            }
        )
    });


    $("#updateWhiteList").click(function() {
        $("#fileId").val("");
        $("#fileName").text("");
        $("#fileName").hide();
        $.ajax({
            url: '/getWhiteList',
            type: 'GET',
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", sessionStorage.getItem("fileSystemToken"));
            },
            success: function (response) {
                $("#white-list").val(response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });

    function setIp(obj) {
        let fileId = $(obj).parent().siblings().eq(1).children("a").attr("id");
        let fileName = $(obj).parent().siblings().eq(1).text();
        $("#fileId").val(fileId);
        $("#fileName").text(fileName);
        $.ajax({
            url: '/getWhiteList?id=' + fileId,
            type: 'GET',
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", sessionStorage.getItem("fileSystemToken"));
            },
            success: function (response) {
                $("#white-list").val(response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    }

    $("#confirm-update-white-list").click(function () {
        let whiteList = $("#white-list").val();
        let fileId = $("#fileId").val();
        let formData = new FormData();
        formData.set("id", fileId);
        formData.set("whiteList", whiteList);
        formRequest('/updateWhiteList', formData,
            function (response) {
                if(redirectLogin(response)) {
                    return;
                }
                if (response == "1") {
                    if(fileId != null && fileId != "") {
                        alert("限定IP修改成功");
                    } else {
                        alert("白名单修改成功");
                    }
                    $("#updateWhiteListModal").modal("hide");
                } else {
                    alert("修改失败");
                }
            }
        )
    });

    function redirectLogin(response) {
        if (response == "-1") {
            window.location.href = "/login";
            return true;
        }
        return false;
    }

    function isShowUpdatePwd() {
        $.ajax({
            url: '/isShowUpdatePwd',
            type: 'GET',
            dataType: "json",
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", sessionStorage.getItem("fileSystemToken"));
            },
            success: function (response) {
                if(response == "1") {
                    $(".updatePwd-div").show();
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    }

    function isShowUpdateWhiteList() {
        $.ajax({
            url: '/isShowUpdateWhiteList',
            type: 'GET',
            dataType: "json",
            beforeSend: function (request) {
                request.setRequestHeader("Authorization", sessionStorage.getItem("fileSystemToken"));
            },
            success: function (response) {
                if(response == "1") {
                    $(".whiteList-div").show();
                    $(".btn-ip").show();
                    $(".btn-del").show();
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    }

</script>
</body>

</html>